import 'package:hive/hive.dart';
import '../models/favorite_model.dart';
import '../../domain/entities/favorite.dart';

/// 收藏本地数据源
/// 使用Hive进行收藏数据的本地存储
class FavoriteLocalDataSource {
  static const String _boxName = 'favorites';
  late Box<FavoriteModel> _box;

  /// 初始化本地存储
  Future<void> init() async {
    _box = await Hive.openBox<FavoriteModel>(_boxName);
  }

  /// 添加收藏
  Future<void> addFavorite(FavoriteModel favorite) async {
    await _box.put(favorite.animeId, favorite);
  }

  /// 移除收藏
  Future<void> removeFavorite(int animeId) async {
    await _box.delete(animeId);
  }

  /// 更新收藏
  Future<void> updateFavorite(FavoriteModel favorite) async {
    await _box.put(favorite.animeId, favorite);
  }

  /// 获取所有收藏
  Future<List<FavoriteModel>> getAllFavorites() async {
    return _box.values.toList();
  }

  /// 根据状态获取收藏
  Future<List<FavoriteModel>> getFavoritesByStatus(FavoriteStatus status) async {
    return _box.values
        .where((favorite) => favorite.status == status.key)
        .toList();
  }

  /// 检查是否已收藏
  Future<bool> isFavorite(int animeId) async {
    return _box.containsKey(animeId);
  }

  /// 获取特定动漫的收藏信息
  Future<FavoriteModel?> getFavorite(int animeId) async {
    return _box.get(animeId);
  }

  /// 清除所有收藏
  Future<void> clearAllFavorites() async {
    await _box.clear();
  }

  /// 获取收藏统计
  Future<Map<String, int>> getFavoriteStats() async {
    final stats = <String, int>{};
    
    // 初始化统计
    for (final status in FavoriteStatus.values) {
      stats[status.key] = 0;
    }
    
    // 统计每个状态的数量
    for (final favorite in _box.values) {
      stats[favorite.status] = (stats[favorite.status] ?? 0) + 1;
    }
    
    return stats;
  }

  /// 获取收藏总数
  Future<int> getFavoriteCount() async {
    return _box.length;
  }

  /// 搜索收藏
  Future<List<FavoriteModel>> searchFavorites(String query) async {
    if (query.isEmpty) return getAllFavorites();
    
    final lowerQuery = query.toLowerCase();
    return _box.values.where((favorite) {
      final animeData = favorite.animeData;
      final title = (animeData['title'] ?? '').toString().toLowerCase();
      final titleJapanese = (animeData['title_japanese'] ?? '').toString().toLowerCase();
      final titleEnglish = (animeData['title_english'] ?? '').toString().toLowerCase();
      
      return title.contains(lowerQuery) ||
             titleJapanese.contains(lowerQuery) ||
             titleEnglish.contains(lowerQuery);
    }).toList();
  }

  /// 按添加日期排序获取收藏
  Future<List<FavoriteModel>> getFavoritesSortedByDate({bool ascending = false}) async {
    final favorites = await getAllFavorites();
    favorites.sort((a, b) {
      final comparison = a.addedDateTimestamp.compareTo(b.addedDateTimestamp);
      return ascending ? comparison : -comparison;
    });
    return favorites;
  }

  /// 按评分排序获取收藏
  Future<List<FavoriteModel>> getFavoritesSortedByScore({bool ascending = false}) async {
    final favorites = await getAllFavorites();
    favorites.sort((a, b) {
      final aScore = a.personalScore ?? 0.0;
      final bScore = b.personalScore ?? 0.0;
      final comparison = aScore.compareTo(bScore);
      return ascending ? comparison : -comparison;
    });
    return favorites;
  }

  /// 获取最近添加的收藏
  Future<List<FavoriteModel>> getRecentFavorites({int limit = 10}) async {
    final favorites = await getFavoritesSortedByDate(ascending: false);
    return favorites.take(limit).toList();
  }
} 